import pymysql

from config import DBTest


class DBUtil(object):
    conn = None
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=DBTest.HOST, port=DBTest.PORT, user=DBTest.USER, password=DBTest.PASSWORD,
                                       database=DBTest.DATABASE, charset=DBTest.CHARSET)
            return cls.conn

    @classmethod
    def __conn_close(cls):
        if cls.conn:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls,sql):
        cursor = None
        res = None
        try:
            cursor = cls.__get_conn().cursor()
            cursor.execute(sql)
            res = cursor.fetchone()
        except Exception as e:
            print(e)
            raise e
        finally:
            if cursor:
                cursor.close()
            cls.__conn_close()
            return res

    @classmethod
    def uid_db(cls,sql):
        cursor = None
        try:
            cursor = cls.__get_conn().cursor()
            cursor.execute(sql)
            cls.conn.commit()
            # cls.__get_conn().commit()
            print(id(cls.conn))
            print(id(cls.__get_conn()))
        except Exception as e:
            print(e)
            if cls.__get_conn():
                cls.__get_conn().rollback()
        finally:
            if cursor:
                cursor.close()
            cls.__conn_close()

if __name__ == '__main__':
        # data = DBUtil.select_one("select * from t_book;")
        # print(data)
        sql = "delete from bs_user where mobile = '18872654535';"
        DBUtil.uid_db(sql)
